package com.lei.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.eduservice.entity.EduSubject;
import com.lei.eduservice.entity.excel.SubjectData;
import com.lei.eduservice.service.EduSubjectService;
import com.lei.servicebase.exception.GuliException;
import io.swagger.models.auth.In;

import java.util.HashMap;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class SubjectDataListener extends AnalysisEventListener<SubjectData> {

    //AnalysisEventListener无法交给Spring管理
    public EduSubjectService subjectService;

    public HashMap<String,Integer> map;

    public SubjectDataListener() {
    }

    public SubjectDataListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
        this.map=new HashMap<String,Integer>();
        //this.map.put("oneSuccessData",0);
        //this.map.put("oneRepeatData",0);
        this.map.put("successData",0);
        this.map.put("repeatData",0);
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {

        if (subjectData==null){
            throw new GuliException(20001,"文件数据为空");
        }

        EduSubject oneSubject = this.exitsOneSubject(subjectService, subjectData.getOneSubjectName());
        if (oneSubject==null){
            oneSubject= new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(oneSubject);
        }

        String pid = oneSubject.getId();
        //判断二级分类
        EduSubject twoSubject = this.exitsTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if (twoSubject==null){
            twoSubject= new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(twoSubject);
            this.map.put("successData",this.map.get("successData")+1);
        }else {
            this.map.put("repeatData",this.map.get("repeatData")+1);
        }
    }

    //判断一级分类是否重复
    private EduSubject exitsOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }
    //判断二级分类是否重复
    private EduSubject exitsTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
